package com.wms.tool;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONObject;
import com.wms.client.HttpClientBuild3false;


public class ReadAndWriteExcel {

	private static final String fileName = Contant.getProperties().get("fileName").toString();

	/**
	 * Excel 全部
	 */
	public static void ReadAndWriteGo(){
		readyGo(null);
	}

	/**
	 * 区间
	 * 
	 * @param period
	 *            (*~*)
	 */
	public static void ReadAndWriteGo(String period) {
		String[] split = period.split("~");
		if (split.length != 2) {
			System.out.println("参数有问题!");
			return;
		}
		int begin = Integer.valueOf(split[0]);
		int end = Integer.valueOf(split[1]);
		if (begin > end && end > 0) {
			System.out.println("起始值有问题!");
			return;
		}
		List<Integer> target = new ArrayList<Integer>();
		for (int i = begin; i <= end; i++) {
			target.add(i);
		}
		readyGo(target);

	}

	/**
	 * 多行/单行
	 * 
	 * @param param(1,2,3)/(1)
	 */
	public static void ReadAndWriteGo(int... params) {
		if (params.length == 0) {
			System.out.println("参数有问题!");
			
		}
		List<Integer> target = new ArrayList<Integer>();
		for (int i = 0; i < params.length; i++) {
			if (params[i] > 0) {
				target.add(params[i]);
			}
		}
		readyGo(target);
	}

	/**
	 * 
	 * @param targetLine
	 */
	private static void readyGo(List<Integer> targetLine) {
		try (FileInputStream ipt = new FileInputStream(fileName);
				XSSFWorkbook wb = new XSSFWorkbook(ipt);
				FileOutputStream output = new FileOutputStream(fileName)) {
			XSSFSheet sheetAt = wb.getSheetAt(0);//第一张表
			// 第一行开始读
			int startRow = 0;
			XSSFRow hRow = sheetAt.getRow(startRow);
			Iterator<Cell> hCell = hRow.cellIterator();

			// 去读取指定头的Index
			Map<String, Integer> title2Index = new HashMap<String, Integer>();
			while (hCell.hasNext()) {
				Cell currentCell = hCell.next();
				title2Index.put(currentCell.getStringCellValue(), currentCell.getColumnIndex());
			}
			// 区间
			if (CollectionUtils.isNotEmpty(targetLine)) {
				for (Integer integer : targetLine) {
					Row dRow = sheetAt.getRow(integer - 1);
					editSomeRowByResp(dRow, title2Index);
				}
				// 全部
			} else {
				Iterator<Row> rowIterator = sheetAt.rowIterator();
				while (rowIterator.hasNext()) {
					Row dRow = rowIterator.next();
					editSomeRowByResp(dRow, title2Index);
				}
			}
			// System.out.println("SUCCESS !!");
			wb.write(output);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param dRow
	 * @param title2Index
	 *            调用Httpclient.doPostJson()
	 */
	private static void editSomeRowByResp(Row dRow, Map<String, Integer> title2Index) {
		int rowNum = dRow.getRowNum();
		if (rowNum == 0) {
			return;
		}
		Cell urlCell = dRow.getCell(title2Index.get("PATH"));
		Cell paramsCell = dRow.getCell(title2Index.get("Params"));
				
		// 请求客户端 HttpClientBuild.doPost
		JSONObject respJson = HttpClientBuild3false.doPost(urlCell.getStringCellValue(),paramsCell.getStringCellValue()); // New
		
		//		String currentStr = respJson == null ? "" : respJson.toJSONString();
		String currentStr = respJson.toJSONString();
		
		Cell respCell = dRow.getCell(title2Index.get("Response")); // Exist
		if (respCell == null) {
			respCell = dRow.createCell(title2Index.get("Response"));
			respCell.setCellValue(currentStr);
		} else {
			String preResp = respCell.getStringCellValue();
			if (!currentStr.equals(preResp)) {
				respCell.setCellValue(currentStr);
			}
		}
		
	}
	
	
	
	/**
	 * 
	 * 拼接参数
	 */
//	public static void Splicing_parameters(){
//		try {
//			XSSFWorkbook wb = new XSSFWorkbook("G:/waybill1.xlsx");
//			XSSFSheet st = wb.getSheetAt(0);
//			st.rowIterator().forEachRemaining(action -> {
//				String packCode = action.getCell(0).getStringCellValue();
//				String waybill = BigDecimal.valueOf(action.getCell(1).getNumericCellValue()).toPlainString();
//				String weight = Double.valueOf(action.getCell(2).getNumericCellValue()).toString();
//				System.out.println(packCode+"======"+waybill+"===="+weight);
//                
//				String str = "{\"packageCode\": \""+packCode+"\",\"waybillCode\": "+waybill+",\"weight\": "+weight+",\"warehouseId\": 40595459210743809,\"expressId\": 40598008034766849,\"goodsOwnerId\": 10091521288556555}";
//				String url="https://tms.youhaodongxi.com/waybill/weight";
//				HttpClientBuild.doPost(url,str);
//			});
//			wb.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}

//	}
}
